package com.hb.unic.websupport.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.MDC;

import com.hb.unic.core.log.support.ILoggerConsts;
import com.hb.unic.core.util.generator.KeyCreator;

/**
 * traceId的过滤器
 *
 * @author Mr.huang
 * @since 2020/4/21 9:07
 */
public class TraceIdHttpFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        try {
            // 初始化traceId
            HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
            String traceId = httpServletRequest.getHeader(ILoggerConsts.TRACE_ID);
            if (traceId == null) {
                traceId = KeyCreator.generate(ILoggerConsts.TRACE_ID_RANDOM_LENGTH);
            }
            MDC.put(ILoggerConsts.TRACE_ID, traceId);
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 销毁traceId
            MDC.clear();
        }
    }

}
